<template>
  <div class="employees-container">
    <el-dialog title="新增员工" :visible.sync="showDialog">
      <EmpDialog @close="close" />
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="showDialogRole">
      <assignRoles v-if="showDialogRole" :cur-employees-id="curId" @closeDialog="closeDialog" />
    </el-dialog>
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button
            v-allow="'export'"
            type="danger"
            size="small"
            @click="EmportExcel"
          >excel导出</el-button>
          <el-button type="primary" size="small" @click="doAdd">
            新增员工
          </el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexAdd" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              类型：{{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="correctionTime" sortable />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="doView(scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoles(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="doDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="pagesize.size"
            :page-sizes="[2,5,10]"
            @current-change="pageChange"
            @size-change="pagesizeChange"
          />
        </el-row>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getEmployees, delEmployees } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './Empdialog'
import assignRoles from './assignRoles'
export default {
  components: {
    EmpDialog,
    assignRoles
  },
  data() {
    return {
      pagesize: {
        page: 1, // 当前页面
        size: 10 // 每页显示几条数据
      },
      total: 0,
      list: [],
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    indexAdd(index) {
      const page = this.pagesize.page // 当前页码
      const pagesize = this.pagesize.size // 每页条数
      return index + 1 + (page - 1) * pagesize
    },
    // 获取员工信息
    async loadEmployees() {
      const res = await getEmployees(this.pagesize)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 格式化
    formatEmployment(num) {
      // 从hireType中 通过id找到对应的元素的value
      // const item = EmployeeEnum.hireType.find(it => it.id === num)
      // if (item) {
      //   return item.value
      // } else {
      //   return '不能确定'
      // }

      // 代码优化
      const hireType = EmployeeEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
      return hireType[num] || '未知'
    },
    // 监听每页显示多少页变化的事件
    pagesizeChange(sizepage) {
      this.pagesize.size = sizepage
      this.loadEmployees()
    },
    // 监听当前页面改变的事件
    pageChange(curpage) {
      this.page = 1
      this.pagesize.page = curpage
      this.loadEmployees()
    },
    // 删除员工信息
    doDel(id) {
      this.$confirm('你确定要删除此部门吗?, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployees(id)
        this.loadEmployees()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch((err) => {
        this.$message({
          type: 'info',
          message: err.message
        })
      })

      if (this.list.length === 1) {
        this.params.page--
        if (this.params.page === 0) {
          this.params.page = 1
        }
      }
    },
    // 新增员工
    doAdd() {
      this.showDialog = true
    },
    // 关闭弹窗
    close() {
      console.log(222)
      this.showDialog = false
    },
    // 子传父返回处理Excel数据
    doImport(data) {
      this.list = data
    },
    // 导出Excel
    EmportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getEmployees(this.pagesize)
        const rows = res.data.rows
        rows.map(item => {
          if (item.formOfEmployment === 1) {
            item.formOfEmployment = '正式'
          } else {
            item.formOfEmployment = '非正式'
          }
        })
        const map = {
          'id': '编号',
          'password': '密码',
          'mobile': '手机号',
          'username': '姓名',
          'timeOfEntry': '入职日期',
          'formOfEmployment': '聘用形式',
          'correctionTime': '转正日期',
          'workNumber': '工号',
          'departmentName': '部门',
          'staffPhoto': '头像地址'
        }
        const header = Object.keys(rows[0])
        console.log(header)
        const headerZH = header.map(key => map[key])
        console.log(headerZH)
        const data = rows.map(item => Object.values(item))
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: headerZH, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 查看员工详情
    doView(id) {
      this.$router.push('/detail?id=' + id)
    },
    // 分配角色弹出窗口
    assignRoles(id) {
      this.showDialogRole = true
      this.curId = id
    },
    // 分配角色弹框关闭
    closeDialog() {
      this.showDialogRole = false
      this.loadEmployees()
    }
  }
}
</script>
